package com.ruoyi.sqlbuilder.execute.handler;

import com.ruoyi.sqlbuilder.domain.Columns;
import com.ruoyi.sqlbuilder.domain.KeyColumnUsage;
import com.ruoyi.sqlbuilder.domain.Statistics;
import com.ruoyi.sqlbuilder.execute.constants.ConvertConstants;
import com.ruoyi.sqlbuilder.execute.convert.SqlHandler;
import com.ruoyi.sqlbuilder.execute.relation.MysqlToDmColumnType;
import com.ruoyi.sqlbuilder.execute.util.ActSqlUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * dm数据库转换器
 *
 * @author Yanzy
 */
public class DmSqlHandler extends SqlHandler {

    @Override
    public String createTableHead(String tableName, String tableSchema) {
        StringBuffer head = new StringBuffer();
        head.append("-- ----------------------------\r\n");
        head.append(String.format("-- Table structure for %s\r\n", tableName));
        head.append("-- ----------------------------\r\n");
        head.append(String.format("BEGIN EXECUTE IMMEDIATE 'DROP TABLE %s'; EXCEPTION WHEN OTHERS THEN NULL; END; \r\n", tableName));
        head.append("/ \r\n");
        head.append("\r\n");
        head.append(String.format("CREATE TABLE %s ( \r\n", tableName));
        head.append(" %s \r\n");
        head.append(String.format(") STORAGE(ON \"%s\", CLUSTERBTR);", tableSchema));
        return head.toString();
    }

    @Override
    public String createTableBody(List<Columns> columns) {

        List<String> sqlArr = new ArrayList<>();
        StringBuffer sql;
        // 主键
        List<String> priKeys = new ArrayList<>();
        for (Columns column : columns) {
            sql = new StringBuffer();
            // name
            sql.append(StringUtils.SPACE).append("\"").append(column.getColumnName()).append("\"").append(StringUtils.SPACE);
            // varchar(12)
            sql.append(handleColumnType(column)).append(handlePrecision(column)).append(StringUtils.SPACE);
            if (!"auto_increment".equalsIgnoreCase(column.getExtra())) {
                // not null
                String notNullPre = handleNotNullPre(column);
                if (StringUtils.isNotBlank(notNullPre)) {
                    sql.append(notNullPre).append(StringUtils.SPACE);
                }
                // default value
                String defaultValue = handleDefaultValue(column);
                if (StringUtils.isNotBlank(defaultValue)) {
                    sql.append(defaultValue).append(StringUtils.SPACE);
                }
            }
            if ("PRI".equalsIgnoreCase(column.getColumnKey())) {
                priKeys.add("\"" + column.getColumnName() + "\"");
            }
            sqlArr.add(sql.toString());
        }
        if (CollectionUtils.isNotEmpty(priKeys)) {
            sqlArr.add(StringUtils.SPACE + handlePrimaryKey(priKeys));
        }
        return StringUtils.join(sqlArr, ",\r\n");
    }

    @Override
    public String handleColumnType(Columns columns) {
        // 字段类型处理
        // 除类型对应外 加 包含特殊处理方式
        if ("tinyint(1)".equalsIgnoreCase(columns.getColumnType())) {
            return "INT";
        }
        if ("longblob".equalsIgnoreCase(columns.getColumnType())) {
            return "BLOB";
        }

        StringBuilder sql = new StringBuilder();
        sql.append(MysqlToDmColumnType.getRelationType(columns.getDataType()));
        if ("auto_increment".equalsIgnoreCase(columns.getExtra())) {
            sql.append(" IDENTITY(2046,1) NOT NULL UNIQUE");
            // 增加自增值
            autoPrkTables.add(columns.getTableName());
        }
        return sql.toString();
    }

    @Override
    public String handlePrimaryKey(List<String> primaryKeys) {

        StringBuilder sql = new StringBuilder(StringUtils.EMPTY);
        if (CollectionUtils.isNotEmpty(primaryKeys)) {
            sql.append("CLUSTER PRIMARY KEY (").append(StringUtils.join(primaryKeys, ",")).append(")");
        }
        return sql.toString();
    }

    @Override
    public String handleTableValue(List<Columns> columns, Map<String, Object> values, String tableName) {
        // 处理数据与字段对应关系 转换为insert语句
        StringBuilder sql = new StringBuilder();
        // 组装所有字段
        sql.append(String.format("INSERT INTO %s (", tableName));
        List<String> names = columns.stream().map(Columns::getColumnName).collect(Collectors.toList());
        sql.append(StringUtils.join(names, ","))
                .append(") VALUES ( ");
        List<String> columnValues = new ArrayList<>();
        for (Columns column : columns) {
            String columnName = column.getColumnName();
            if (!values.containsKey(columnName)) {
                columnValues.add("NULL");
                continue;
            }
            if (null == values.get(columnName)) {
                columnValues.add("NULL");
                continue;
            }
            // 特殊处理
            if ("BYTES_".equalsIgnoreCase(columnName)) {
                columnValues.add(ActSqlUtil.getBytesValues(ConvertConstants.DB_DM, values.get("NAME_").toString()));
            } else if (values.get(columnName).equals(true) || values.get(columnName).equals(false)) {
                columnValues.add(String.format("'%s'", values.get(columnName).equals(true) ? 1 : 0));
            } else {
                String v = values.getOrDefault(columnName, "").toString();
                v = v.replaceAll("\\\\", "\\\\\\\\");
                v = v.replaceAll("'", "''");
                columnValues.add(String.format("'%s'", v));
            }
        }
        sql.append(StringUtils.join(columnValues, ","));
        sql.append(" );");
        return sql.toString();
    }

    @Override
    public String handleInsertHead(String tableName) {
        if (autoPrkTables.contains(tableName)) {
            return "-- ----------------------------\r\n" +
                    String.format("-- Records of %s \r\n", tableName) +
                    "-- ----------------------------\r\n" +
                    String.format("SET IDENTITY_INSERT %s on;", tableName);
        }
        return StringUtils.EMPTY;
    }

    @Override
    public String handleInsertFoot(String tableName) {
        if (autoPrkTables.contains(tableName)) {
            return String.format("SET IDENTITY_INSERT %s OFF;", tableName);
        }
        return StringUtils.EMPTY;
    }

    @Override
    public String handleForeignKey(KeyColumnUsage keyColumnUsage) {
        if (keyColumnUsage.getPositionInUniqueConstraint() == null || keyColumnUsage.getReferencedTableSchema() == null
                || keyColumnUsage.getReferencedTableName() == null || keyColumnUsage.getReferencedColumnName() == null) {
            return StringUtils.EMPTY;
        }
        return String.format("ALTER TABLE %s ADD constraint %s FOREIGN KEY (%s) REFERENCES %s (%s);",
                keyColumnUsage.getTableName(), keyColumnUsage.getConstraintName(), keyColumnUsage.getColumnName(),
                keyColumnUsage.getReferencedTableName(), keyColumnUsage.getReferencedColumnName());
    }

    @Override
    public String handleIndex(Statistics statistics) {
        String sql;
        if (statistics.getNonUnique() == 0) {
            // 唯一索引
            sql = String.format("CREATE UNIQUE INDEX %s ON %s(\"%s\");", statistics.getIndexName(),
                    statistics.getTableName(), statistics.getColumnName());
            ;
        } else {
            sql = String.format("CREATE INDEX %s ON %s(\"%s\");", statistics.getIndexName(),
                    statistics.getTableName(), statistics.getColumnName());
        }
        return sql;
    }

    @Override
    public String handleIndexList(List<Statistics> statistics) {
        StringBuilder sql = new StringBuilder("CREATE ");
        List<String> column = new ArrayList<>();
        boolean isUnique = false;
        for (Statistics statistic : statistics) {
            if (statistic.getNonUnique() == 0) {
                isUnique = true;
            }
            column.add(String.format("\"%s\"", statistic.getColumnName()));
        }
        if (isUnique) {
            sql.append("UNIQUE ");
        }
        sql.append("INDEX %s ON %s( %s );");
        return String.format(sql.toString(), statistics.get(0).getIndexName(), statistics.get(0).getTableName(), StringUtils.join(column, ","));
    }
}
